package com.xaut.outpatientsystem.medicinalManagement.serviceImpl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.pojo.Case;
import com.example.demo.pojo.Prescribe;
import com.example.demo.service.CaseService;
import com.example.demo.service.PrescribeService;
import com.xaut.outpatientsystem.medicinalManagement.pojo.Medicine;
import com.xaut.outpatientsystem.medicinalManagement.pojo.Receipt;
import com.xaut.outpatientsystem.medicinalManagement.service.MedicineService;
import com.xaut.outpatientsystem.medicinalManagement.service.OrderRecordService;
import com.xaut.outpatientsystem.medicinalManagement.service.ReceiptService;
import com.xaut.outpatientsystem.medicinalManagement.util.ExcelToPDFUtil;
import com.xaut.outpatientsystem.medicinalManagement.util.TestFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.OutputStream;
import java.util.*;

@Service
public class OrderRecordServiceImpl implements OrderRecordService {

    @Autowired
    private PrescribeService prescribeService;

    @Autowired
    private ReceiptService receiptService;

    @Autowired
    private CaseService caseService;

    @Autowired
    private MedicineService medicineService;

    @Override
    public String outInExcelById(int id, OutputStream outputStream) {
        // 获取开药表中药品列表，计算药品的总价
        double total = 0.0;
        List<Prescribe> list = prescribeService.searchprescribe(id);
//        List<Prescribe> list = new ArrayList<>();
//        Prescribe prescribe1 = new Prescribe(3, 3, 3, "1111", "122", 123, 1233);
//        Prescribe prescribe2 = new Prescribe(4, 3, 4, "11111", "1122", 13, 5533);
//        Prescribe prescribe3 = new Prescribe(5, 3, 4, "1111221", "1122222", 13, 5533);
//        list.add(prescribe1);list.add(prescribe2);list.add(prescribe3);
        for (Prescribe prescribe : list) {
            System.out.println(prescribe);
            // 判断药品库存是否充分
            if (medicineService.getById(prescribe.getMedicine_id()).getNums() < prescribe.getNum()) {
                System.out.println("药品数量不足！");
                return "error";
            }
            total += 1. * prescribe.getPrice() / 100 * prescribe.getNum();
        }
        for (Prescribe prescribe : list) {
            // 更改药品库存信息
            Medicine medicine = medicineService.getById(prescribe.getMedicine_id());
            medicine.setNums(medicine.getNums() - prescribe.getNum());
            medicineService.updateById(medicine);
        }
        // 获取Case表对应的实体类，从而得到病人姓名...
        List<Case> list2 = caseService.searchCase(id);
        Case cases = list2.get(0);
        // File.separator 的作用相当于 ' \ ',在 windows 中 文件文件分隔符 用 ' \ ' 或者 ' / ' 都可以
        // excel模板所在路径
        String templateFileName = TestFileUtil.getPath() + "demo" + "/" + "template.xlsx";
        System.out.println(templateFileName);
        // excel输出文件的路径
        String index = String.valueOf(System.currentTimeMillis());
        String fileName = "/D:/Code/outpatientsystem/src/main/resources/demo/" + "template" + index + ".xlsx";
        System.out.println(fileName);
        // 获取对象，用于写操作,outputStream文件流写入EasyExcel，使用withTemplate方法调用模板(参数就是模板文件的路径)
        ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(templateFileName).build();
        // 创建一个页签
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        // 这里定义一个自动填充需要遍历的表格类| NewRow(Boolean.TRUE) 自动换行
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
        // 如果有多个list 模板上必须有{前缀.} 这里的前缀就是 data1，然后多个list必须用 FillWrapper包裹
        // 将data的数据完整填充进excelWriter
        excelWriter.fill(list, writeSheet);
        Map<String, Object> map = new HashMap<>();
        Date date = new Date();
        String payee = "小刘";
        map.put("date", date);
        map.put("payee", payee);
        map.put("name", cases.getPatients_name());
        map.put("total", total);
        excelWriter.fill(map, writeSheet);
//        // 别忘记关闭流，关闭文件流
        excelWriter.finish();
        System.out.println("akkakkakakk!!");
        // 将收据单信息保存到数据库中
        QueryWrapper<Receipt> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_id", id);
        Receipt one = receiptService.getOne(queryWrapper);
        if (one == null) {
            Receipt receipt = new Receipt();
            receipt.setPayee(payee);
            receipt.setPatientName(cases.getPatients_name());
            receipt.setCaseId(id);
            receipt.setTime(date);
            receipt.setTotal((int) (total * 100));
            receiptService.save(receipt);
        }
        // 根据excel，生成对应的pdf文件
        String excelPath = "/Code/outpatientsystem/src/main/resources/demo/" + "template" + index + ".xlsx";
        String pdfPath = "/pdfResource/" + "template" + index + ".pdf";
        try {
            ExcelToPDFUtil.excelToPdf(excelPath, pdfPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(index);
        return index;
    }
}
